<template>
  <div class="table-box">

    <Table
        ref="table"
        :searchColumns="searchColumns"
        description_keywords="projectManage"
        @getTableList="getTableList"
    >
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="showProjectFrom('create')">新增项目</el-button>
        <!--        <el-button  type="primary" :icon="Upload" plain @click="">批量添加菜单</el-button>-->
        <!--        <el-button  type="primary" :icon="Download" plain @click="">导出菜单数据</el-button>-->
        <!--        <el-button type="primary" plain @click="">To 子集详情页面</el-button>-->
        <!--        <el-button type="danger" :icon="Delete" plain  @click="">-->
        <!--          批量删除菜单-->
        <!--        </el-button>-->
      </template>
      <template #table>
        <!-- 表格主体 -->
        <el-table :data="tableList"
                  row-key="id"
                  border
                  style="width: 100%">
          <el-table-column prop="project_name" fixed="left" align="center" label="项目名称" width="200"/>
          <el-table-column prop="meta.icon" align="center" label="项目图标" width="150">
            <template #default="scope">
              <div v-if="scope.row.project_icon" class="table-pic">
                <img :src="baseURL + scope.row.project_icon" alt="">
              </div>
              <span v-else>暂无项目图标</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" align="center" label="项目管理员" min-width="200"/>
          <el-table-column prop="description" align="center" label="项目成员" min-width="200"/>
          <el-table-column prop="is_open" align="center" label="是否公开项目" width="150">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.is_open"
                  @change=""
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
              />
            </template>
          </el-table-column>
          <el-table-column prop="description" align="center" label="项目描述" min-width="200"/>
          <el-table-column prop="create_time" align="center" label="创建时间" width="170"/>
          <el-table-column prop="update_time" align="center" label="最近修改时间" width="170"/>
          <el-table-column align="center" fixed="right" label="操作" min-width="270">
            <template #default="scope">
              <el-button
                  @click="showProjectFrom('update',scope)"
                  size="small">编辑
              </el-button>
              <el-button
                  @click=""
                  size="small">上移
              </el-button>
              <el-button
                  @click=""
                  size="small">下移
              </el-button>
              <el-button
                  size="small"
                  @click=""
                  type="danger">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </Table>

    <el-dialog v-model="projectFormDialogVisible" :title="projectFormDialogTitle" width="800" draggable>

      <el-form ref="projectFormRef" :model="projectFormData" :rules="projectRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称:" prop="project_name">
              <el-input style="width: 100%;"
                        v-model="projectFormData.project_name"
                        placeholder=请输入项目名称>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目描述:">
              <el-input style="width: 100%;"
                        v-model.trim="projectFormData.description"
                        type="textarea"
                        placeholder=请输入项目描述>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目图标:">
              <el-upload
                  class="pic-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="uploadSectionFile"
                  :before-upload="beforeProjectIconUpload"
                  :on-remove="handleRemove"
              >
                <img v-if="projectFormData.project_icon" :src="baseURL + projectFormData.project_icon" alt=""
                     class="pic-img"/>
                <el-icon v-else class="pic-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否公开:">
              <el-switch v-model="projectFormData.is_open">
              </el-switch>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="项目管理员:" prop="project_managers">
              <el-select style="width: 100%;"
                         filterable
                         v-model="projectFormData.project_managers"
                         placeholder="请选择项目管理员">
                <el-option v-for="item in selectUserOption" :label="item.nickname " :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目成员:">
              <el-select style="width: 100%;"
                         multiple
                         collapse-tags
                         collapse-tags-tooltip
                         :max-collapse-tags="1"
                         filterable
                         clearable
                         v-model="projectFormData.project_members"
                         placeholder="请选择项目成员">
                <el-option v-for="item in selectUserOption" :label="item.nickname " :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="">取消</el-button>
          <el-button type="primary" :loading="loading" @click="commitProjectFrom(projectFormRef)">确定
          </el-button>
        </div>
      </template>

    </el-dialog>


  </div>

</template>

<script setup>
import {useProjectStore} from '@/stores/modules/project/project.js'
import {storeToRefs} from "pinia";
import {provide, onMounted, ref, reactive, onBeforeUnmount} from "vue";
import {CirclePlus, Plus} from "@element-plus/icons-vue";
import Table from "@/components/Table/index.vue";
import {
  getProjectApi,
  getProjectListApi,
  postProjectApi,
  postProjectFile
} from "@/api/modules/project/projectManage.js";
import {ElMessage} from "element-plus";
import {getSelectUser} from "@/api/modules/user.js";


const projectStore = useProjectStore()

// 需要搜索的配置项
const searchColumns = ref([
  {label: "项目名称", field: "project_name", searchType: "input"},
])

const tableList = ref([])

onMounted(() => {
  getTableList()
})

const table = ref(null)
const searchArgsDict = ref({})
const getTableList = async (searchArgs) => {
  const {data} = await getProjectListApi(searchArgs)
  searchArgsDict.value = searchArgs
  tableList.value = data.data
  table.value.pageable.pageNum = data.page
  table.value.pageable.pageSize = data.pagesize
  table.value.pageable.total = data.total
}


const projectFormDialogVisible = ref(false)
const projectFormDialogTitle = ref("")
const projectFormData = ref({})
const showProjectFrom = (formType, scope = undefined) => {
  projectFormDialogVisible.value = true
  getSelectUserOption()

  if (formType === "create") {
    projectFormDialogTitle.value = "新增项目"
  }
  if (formType === "update") {
    projectFormDialogTitle.value = "编辑项目"
    let project_id = scope.row.id
    console.log(project_id)
    getProjectApi(project_id).then(res => {
      projectFormData.value = res
    })
  }

}


const baseURL = import.meta.env.VITE_API_URL

const uploadSectionFile = (params) => {
  const file = params.file
  // const fileType = file.type
  // const isImage = fileType.indexOf("image") !== -1
  // const isLt4M = file.size / 1024 / 1024 < 4;
  // 这里常规检验，看项目需求而定
  // if (!isImage) {
  //   ElMessage.error("只能上传图片格式png、jpg、gif!");
  //   return;
  // }
  // 根据后台需求数据格式
  const form = new FormData();
  // 文件对象
  form.append("file", file);
  // form.append("Content-Type", 'multipart/form-data');
  // 上传头像的请求方法
  postProjectFile(form).then(res => {
    projectFormData.value.project_icon = res.data
  })
}


const beforeProjectIconUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('头像图片不能大于 4MB!')
    return false
  }
  if (["image/png", "image/jpg", "image/jpeg", "image/gif"].indexOf(rawFile.type) === -1) {
    ElMessage.error('请上传png,jpg,jpeg,gif格式的图片')
    return false
  }
  return true
}

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const selectUserOption = ref([])
const getSelectUserOption = async () => {
  await getSelectUser().then(res => {
    selectUserOption.value = res.data
  })
}

const projectFormRef = ref(null);
const projectRules = reactive({
  project_name: [{required: true, message: "请输入项目名称", trigger: "blur"}],
  project_managers: [{required: true, message: "请选择项目管理员", trigger: "change"}],
});


const loading = ref(false);
const commitProjectFrom = (formEl) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      if (projectFormData.value.id) {
        console.log("编辑")
      } else {
        postProjectApi(projectFormData.value).then(res => {

          ElMessage.success("新增成功");
          projectFormDialogVisible.value = false;
          getTableList(searchArgsDict.value);
          // 更新项目后回调
          $eventBus.emit("updateProject")

        })
      }

    } finally {
      loading.value = false;
    }
  })
}

const cancel = () => {

}

</script>


<style scoped>

.pic-uploader .pic-img {
  width: 50px;
  height: 50px;
  display: block;
  border-radius: 50%;
}

</style>

<style>

.pic-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.pic-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.pic-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
</style>

